package com.yh.csx.crm.service.vo;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.Data;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * PageWrap class
 *
 * @author huyalin
 * @date 2019/2/26
 */
@Data
public class PageWrap<T> {

    private int pageNo;

    private int pageSize;

    private int totalNum;

    private int pages;

    private List<T> result;

    public void setValue(Page page) {
        pageNo = page.getPageNum();
        pageSize = page.getPageSize();
        totalNum = (int) page.getTotal();
        pages = page.getPages();
    }

    public static <T> PageWrap<T> wrap(List<T> list) {
        PageInfo<T> pageInfo = PageInfo.of(list);
        PageWrap<T> wrap = new PageWrap<>();
        wrap.pageNo = pageInfo.getPageNum();
        wrap.pageSize = pageInfo.getPageSize();
        wrap.totalNum = (int) pageInfo.getTotal();
        wrap.pages = pageInfo.getPages();
        wrap.result = pageInfo.getList();
        return wrap;
    }

    public static <T, R> PageWrap<R> wrap(List<T> list, Function<T, R> convert) {
        PageInfo<T> pageInfo = PageInfo.of(list);
        PageWrap<R> wrap = new PageWrap<>();
        wrap.pageNo = pageInfo.getPageNum();
        wrap.pageSize = pageInfo.getPageSize();
        wrap.totalNum = (int) pageInfo.getTotal();
        wrap.pages = pageInfo.getPages();
        wrap.result = pageInfo.getList() == null ? null : pageInfo.getList().stream().map(convert).collect(Collectors.toList());
        return wrap;
    }
}
